package com.six.clinic.common.component;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: shinan
 * @Version: 1.8
 * @create: 2020/12/1 15:20
 * @Description: TODO
 */
public class MyEnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    /**
     * 枚举类型
     */
    private final Class<E> type;

    /**
     * 构造器
     * @param type 枚举的类型
     */
    public MyEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        } else {
            this.type = type;
        }
    }

    /**
     *
     * @param ps SQL语句
     * @param i 当前属性在sql语句中占位的索引
     * @param parameter 传入的枚举参数
     * @param jdbcType 数据库类型
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        //使用toString方法来进行值的设置，需重写枚举的toString方法
        if (jdbcType == null) {
            //为指定索引位置的属性设置值 parameter.toString()重写toString后返回的是状态码
            ps.setString(i, parameter.toString());
        } else {
            ps.setObject(i, parameter.toString(), jdbcType.TYPE_CODE);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return get(rs.getString(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return get(rs.getString(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return get(cs.getString(columnIndex));
    }

    /**
     * 根据value获取枚举对象
     *
     * @param v
     * @param <E>
     * @return
     */
    private <E extends Enum<E>> E get(String v) {
        if (v == null) {
            return null;
        }
        if (!StringUtils.isEmpty(v)) {
            Method method = null;
            try {
                method = type.getMethod("getEnum", Integer.class);
                return (E) method.invoke(type, Integer.parseInt(v));
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            return null;
        }
    }
}